package com.sky.directdeal.activity;


import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.sky.directdeal.R;
import com.sky.directdeal.adapter.GridMenuAdapter;
import com.sky.directdeal.adapter.NavDrawerListAdapter;
import com.sky.directdeal.constants.Constants;
import com.sky.directdeal.helper.HomeActvityHelper;
import com.sky.directdeal.listener.UiUpdateListener;
import com.sky.directdeal.manager.SharedPreferenceManager;
import com.sky.directdeal.utils.Utils;
import com.sky.local_ads.fetch_category.CategoryList;
import com.sky.local_ads.fetch_category.CategoryResponse;
import com.sky.local_ads.offer_cat_list.OfferCategoryResponse;
import com.sky.local_ads.offer_cat_list.OffersCategoryList;

public class HomeActivity extends BaseActivity {
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ListView mDrawerRight;
	private ActionBarDrawerToggle mDrawerToggle;

	// nav drawer title
	private CharSequence mDrawerTitle;

	// used to store app title
	private CharSequence mTitle;

	private NavDrawerListAdapter adapter;
	
	 private GridView menuGridView;
	 
	 private boolean isService=false;
	 
	 private List<OffersCategoryList> offersList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		setHeaderTitle(getResources().getString(R.string.today_deal));
		initUiElements();
		getCategory();
		mTitle = mDrawerTitle = getTitle();

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
		mDrawerList.setOnItemClickListener(drawerOnItemClickListener);
		mDrawerRight=(ListView)findViewById(R.id.right_drawer);
		mDrawerRight.setOnItemClickListener(settingsDrawerClickListener);
		intializeDrawerMenu();
		initializeSettingsDrawer();

		// enabling action bar app icon and behaving it as toggle button
		setHomeUp();

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, //nav menu toggle icon
				R.string.app_name, // nav drawer open - description for accessibility
				R.string.app_name // nav drawer close - description for accessibility
		) {
			@SuppressLint("NewApi")
			public void onDrawerClosed(View view) {
				setTitle(mTitle);
				supportInvalidateOptionsMenu();
			}

			@SuppressLint("NewApi")
			public void onDrawerOpened(View drawerView) {
				setTitle(mDrawerTitle);
				supportInvalidateOptionsMenu();
				
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			//displayView(0);
		}
		//getTodayDeal();
	}
	
	private void getTodayDeal(){
		if(!isService && checkInternet(true)){
			isService=true;
			HomeActvityHelper.getTodayDealServiceCall(getApplicationContext(), getTodayDealListener);
			
		}else{
			mDrawerLayout.closeDrawers();
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		new MenuInflater(getApplication()).inflate(R.menu.home, menu); 
		return super.onCreateOptionsMenu(menu);
		
	}
	
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch (item.getItemId()) {
		case R.id.action_settings:
			/*Intent localtionIntent=new Intent(HomeActivity.this,UserLocationActivity.class);
			startActivity(localtionIntent);*/
			mDrawerLayout.openDrawer(mDrawerRight);
			break;

		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onStart() {
		checkAppUpdate();
		super.onStart();
	}
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private OnItemClickListener drawerOnItemClickListener =new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapter, View arg1, int pos,
				long arg3) {
			OffersCategoryList categoryList=(OffersCategoryList)adapter.getAdapter().getItem(pos);
			Intent offerListIntent=new Intent(HomeActivity.this,OfferListActivity.class);
			offerListIntent.putExtra(Constants.INTENT_CATEGORYY_ID, categoryList.getCatId());
			startActivity(offerListIntent);
		}
	};
	
	private void initUiElements(){
		menuGridView=(GridView)findViewById(R.id.menurGidView);
		RelativeLayout storeCallInnerLayout = (RelativeLayout)findViewById(R.id.storeCallLayout);
		storeCallInnerLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Utils.callNumber("9952995268", HomeActivity.this);
			}
		});
	}
	
	private void intializeDrawerMenu()
	{
		/*List<CategoryList> categoryList=Utils.categoryResponse.getCategoryList();
		
				// setting the nav drawer list adapter
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				categoryList);
		mDrawerList.setAdapter(adapter);*/
	}
	
	
	private void initializeSettingsDrawer(){
		String settingsMenuArray[]=getResources().getStringArray(R.array.settings_menu_array);
		List<String> settingsList=new ArrayList<String>();
		for(String menuItem:settingsMenuArray){
			settingsList.add(menuItem);
		}
		ArrayAdapter<String> adpater=new ArrayAdapter<String>(this,R.layout.setttings_row_layout, settingsList);
		mDrawerRight.setAdapter(adpater);
	}
	
	
	private void getCategory(){
		if(!isService && checkInternet(true)){
			mainCategoryHandler.sendEmptyMessage(Constants.SHOW_PROGRESS_DIALOG);
			isService=true;
			HomeActvityHelper.getCategoryServiceCall(getApplicationContext(), CategoryListListener);
			
		}
	}
	
	private OnItemClickListener settingsDrawerClickListener=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			switch (arg2) {
			case 0:
				Intent localtionIntent=new Intent(HomeActivity.this,UserLocationActivity.class);
				startActivity(localtionIntent);
				break;
				
			case 1:
				break;
			case 2:
				Utils.ShareIntentMessage(HomeActivity.this, getString(R.string.app_share_text));
				break;
			case 3:
				Intent tellUsIntent=new Intent(HomeActivity.this,TelUsActivity.class);
				startActivity(tellUsIntent);
				break;

			default:
				break;
			}
			
		}
	};
	
	private void checkAppUpdate(){
		int updateStatus=0;
		updateStatus=SharedPreferenceManager.getPreferenceValue(getApplicationContext(), SharedPreferenceManager.Keys.UPDATE_TYPE);
		if(updateStatus==Constants.FORCE_UPDATE){
			showAlert(HomeActivity.this, getString(R.string.alert), getString(R.string.new_version_launched), getString(R.string.update_button), positiveListener, getString(R.string.cancel_button), negativeListener);
		}
		
		
	}
	
public DialogInterface.OnClickListener positiveListener=new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
			try {
			    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
			} catch (android.content.ActivityNotFoundException anfe) {
			    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
			}
		}
	};
	
public DialogInterface.OnClickListener negativeListener=new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			finish();
		}
	};
	
	
	private final UiUpdateListener getTodayDealListener=new UiUpdateListener() {
		
		@Override
		public void OnUpdateUI(Object... object) {
			OfferCategoryResponse offerCategoryResponse=(OfferCategoryResponse)object[0];
			isService=false;
			mainCategoryHandler.sendEmptyMessage(Constants.DISMISS_PROGRESS_DIALOG);
			if(offerCategoryResponse!=null && offerCategoryResponse.getStatusCode()==Constants.SUCCESS_CODE && offerCategoryResponse.getStoreOffersList().size()>0){
				offersList=offerCategoryResponse.getStoreOffersList();
				adapter = new NavDrawerListAdapter(HomeActivity.this,
						offersList);
				mDrawerList.setAdapter(adapter);
			}else{
				Toast.makeText(HomeActivity.this, "No offers found", Toast.LENGTH_SHORT).show();
			}
			
		
			
		}
		
		@Override
		public void OnFailure(String errorMessage) {
			isService=false;
			mainCategoryHandler.sendEmptyMessage(Constants.DISMISS_PROGRESS_DIALOG);
			Toast.makeText(HomeActivity.this, "Server failed! try again", Toast.LENGTH_SHORT).show();			
		}
	};
	
private final UiUpdateListener CategoryListListener=new UiUpdateListener() {
		
		@Override
		public void OnUpdateUI(Object... object) {
			CategoryResponse CategoryResponse=(CategoryResponse)object[0];
			isService=false;
			mainCategoryHandler.sendEmptyMessage(Constants.DISMISS_PROGRESS_DIALOG);
			
			if(CategoryResponse!=null && CategoryResponse.getCategoryList().size()>0){
				GridMenuAdapter gridMenuAdapter=new GridMenuAdapter(HomeActivity.this, CategoryResponse.getCategoryList());
				menuGridView.setAdapter(gridMenuAdapter);
				
				menuGridView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
							long arg3) {
						if(checkInternet(true)){
							CategoryList categoryList=(CategoryList)arg0.getItemAtPosition(pos);
							int isChild=categoryList.getIsChild();
							int catId=categoryList.getCategoryId();
							String catName=categoryList.getCategoryName();
							if(isChild==1){
								
								Intent subCatListIntent=new Intent(HomeActivity.this,SubCategoryListActivity.class);
								subCatListIntent.putExtra(Constants.INTENT_CATEGORYY_ID,catId);
								subCatListIntent.putExtra(Constants.INTENT_CATEGORYY_NAME,catName);
								startActivity(subCatListIntent);
							}else{
								Intent businessListIntent=new Intent(HomeActivity.this,BusinessListActivity.class);
								businessListIntent.putExtra(Constants.INTENT_CATEGORYY_ID,catId);
								businessListIntent.putExtra(Constants.INTENT_CATEGORYY_NAME,catName);
								startActivity(businessListIntent);
							}
						}
					}
				});
				
			}
			
		}
		
		@Override
		public void OnFailure(String errorMessage) {
			isService=false;
			mainCategoryHandler.sendEmptyMessage(Constants.DISMISS_PROGRESS_DIALOG);
			Toast.makeText(HomeActivity.this, "Server failed! try again", Toast.LENGTH_SHORT).show();			
		}
	};
}
